package Offer2018.java8;

import org.junit.Test;

import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 构造器引用
 *  和方法引用类似，函数式接口的抽象方法的形参列表和构造器的形参列表一致。
 *  抽象方法的返回值类型即为构造器所属的类的类型。
 */
public class ConstructorRefTest {

    //Supplier<T>中的     T get()
    //Employee的空参构造器 Employee()
    @Test
    public void test1() {
        //普通形式
        Supplier<Employee> s1 = new Supplier<Employee>() {
            @Override
            public Employee get() {
                return new Employee();
            }
        };
        System.out.println(s1.get());

        //lambda
        Supplier<Employee> s2 = () -> new Employee();
        System.out.println(s2.get());

        //构造器引用
        Supplier<Employee> s3 = Employee::new;
        System.out.println(s3.get());
    }


    //Function<T,R>中的R apply(T t)
    //Employee中的  Employee(int id)
    @Test
    public void test2() {
        //普通
        Function<Integer, Employee> f1 = new Function<Integer, Employee>() {

            @Override
            public Employee apply(Integer id) {
                return new Employee(id);
            }
        };
        System.out.println(f1.apply(1));

        //lambda
        Function<Integer, Employee> f2 = id -> new Employee(id);
        System.out.println(f2.apply(2));

        //构造器引用
        Function<Integer, Employee> f3 = Employee::new;
        System.out.println(f3.apply(3));
    }


    //BiFunction<T, U, R>中的R apply(T t,U u)
    //Employee中的             Employee(int id,String name);
    @Test
    public void test3() {
        //普通
        BiFunction<Integer, String, Employee> b1 = new BiFunction<Integer, String, Employee>() {
            @Override
            public Employee apply(Integer id, String name) {
                return new Employee(id, name);
            }
        };
        System.out.println(b1.apply(1, "kylin"));

        //lambda
        BiFunction<Integer, String, Employee> b2 = (id, name) -> new Employee(id, name);
        System.out.println(b2.apply(2, "zs"));

        //构造器引用
        BiFunction<Integer, String, Employee> b3 = Employee::new;
        System.out.println(b3.apply(3, "ww"));
    }
}
